package com.imut.lagain.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imut.lagain.common.Result;
import com.imut.lagain.entity.SystemNotification;
import com.imut.lagain.service.SystemNotificationService;
import com.imut.lagain.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 系统通知控制器
 */
@RestController
@RequestMapping("/system-notifications")
public class SystemNotificationController {
    private static final Logger log = LoggerFactory.getLogger(SystemNotificationController.class);
    
    @Autowired
    private SystemNotificationService notificationService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 获取用户通知列表
     */
    @GetMapping
    public Result<IPage<SystemNotification>> getUserNotifications(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            IPage<SystemNotification> notifications = notificationService.getUserNotifications(userId, page, size);
            return Result.success(notifications);
        } catch (Exception e) {
            log.error("获取用户通知列表失败", e);
            return Result.error("获取通知列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread/count")
    public Result<Long> getUnreadNotificationCount(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long count = notificationService.getUnreadNotificationCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读通知数量失败", e);
            return Result.error("获取未读通知数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取指定类型的通知
     */
    @GetMapping("/type/{type}")
    public Result<List<SystemNotification>> getNotificationsByType(
            @PathVariable String type,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<SystemNotification> notifications = notificationService.getNotificationsByType(userId, type);
            return Result.success(notifications);
        } catch (Exception e) {
            log.error("获取指定类型通知失败", e);
            return Result.error("获取通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读的指定类型通知
     */
    @GetMapping("/type/{type}/unread")
    public Result<List<SystemNotification>> getUnreadNotificationsByType(
            @PathVariable String type,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<SystemNotification> notifications = notificationService.getUnreadNotificationsByType(userId, type);
            return Result.success(notifications);
        } catch (Exception e) {
            log.error("获取未读指定类型通知失败", e);
            return Result.error("获取通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记通知为已读
     */
    @PutMapping("/read/{notificationId}")
    public Result<Boolean> markAsRead(@PathVariable Long notificationId,
                                     HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = notificationService.markAsRead(notificationId, userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("标记通知已读失败", e);
            return Result.error("标记通知已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记所有通知为已读
     */
    @PutMapping("/read/all")
    public Result<Boolean> markAllAsRead(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = notificationService.markAllAsRead(userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("标记所有通知已读失败", e);
            return Result.error("标记所有通知已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记指定类型的通知为已读
     */
    @PutMapping("/read/type/{type}")
    public Result<Boolean> markTypeAsRead(@PathVariable String type,
                                         HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = notificationService.markTypeAsRead(userId, type);
            return Result.success(success);
        } catch (Exception e) {
            log.error("标记指定类型通知已读失败", e);
            return Result.error("标记指定类型通知已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除通知
     */
    @DeleteMapping("/{notificationId}")
    public Result<Boolean> deleteNotification(@PathVariable Long notificationId,
                                              HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = notificationService.deleteNotification(notificationId, userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除通知失败", e);
            return Result.error("删除通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取高优先级未读通知
     */
    @GetMapping("/high-priority")
    public Result<List<SystemNotification>> getHighPriorityUnreadNotifications(
            @RequestParam(defaultValue = "3") Integer minPriority,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<SystemNotification> notifications = 
                notificationService.getHighPriorityUnreadNotifications(userId, minPriority);
            return Result.success(notifications);
        } catch (Exception e) {
            log.error("获取高优先级未读通知失败", e);
            return Result.error("获取高优先级通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取通知详情
     */
    @GetMapping("/{notificationId}")
    public Result<SystemNotification> getNotificationById(@PathVariable Long notificationId,
                                                          HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            SystemNotification notification = notificationService.getNotificationById(notificationId, userId);
            if (notification == null) {
                return Result.error("通知不存在或无权限访问");
            }
            return Result.success(notification);
        } catch (Exception e) {
            log.error("获取通知详情失败", e);
            return Result.error("获取通知详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取通知统计
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getNotificationStatistics(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Map<String, Object> statistics = notificationService.getNotificationStatistics(userId);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取通知统计失败", e);
            return Result.error("获取通知统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取通知摘要
     */
    @GetMapping("/summary")
    public Result<List<Map<String, Object>>> getNotificationSummary(
            @RequestParam(defaultValue = "7") int days,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<Map<String, Object>> summary = notificationService.getNotificationSummary(userId, days);
            return Result.success(summary);
        } catch (Exception e) {
            log.error("获取通知摘要失败", e);
            return Result.error("获取通知摘要失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建胶囊创建通知（内部接口，供其他服务调用）
     */
    @PostMapping("/internal/capsule-created")
    public Result<SystemNotification> createCapsuleCreatedNotification(
            @RequestBody Map<String, Object> request) {
        try {
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            Long triggerUserId = Long.valueOf(request.get("triggerUserId").toString());
            Long capsuleId = Long.valueOf(request.get("capsuleId").toString());
            String capsuleTitle = request.get("capsuleTitle").toString();
            
            SystemNotification notification = notificationService.createCapsuleCreatedNotification(
                receiverId, triggerUserId, capsuleId, capsuleTitle);
            return Result.success(notification);
        } catch (Exception e) {
            log.error("创建胶囊创建通知失败", e);
            return Result.error("创建通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建胶囊打开通知（内部接口，供其他服务调用）
     */
    @PostMapping("/internal/capsule-opened")
    public Result<SystemNotification> createCapsuleOpenedNotification(
            @RequestBody Map<String, Object> request) {
        try {
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            Long triggerUserId = Long.valueOf(request.get("triggerUserId").toString());
            Long capsuleId = Long.valueOf(request.get("capsuleId").toString());
            String capsuleTitle = request.get("capsuleTitle").toString();
            
            SystemNotification notification = notificationService.createCapsuleOpenedNotification(
                receiverId, triggerUserId, capsuleId, capsuleTitle);
            return Result.success(notification);
        } catch (Exception e) {
            log.error("创建胶囊打开通知失败", e);
            return Result.error("创建通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建小偷偷取成功通知（内部接口，供其他服务调用）
     */
    @PostMapping("/internal/thief-success")
    public Result<SystemNotification> createThiefSuccessNotification(
            @RequestBody Map<String, Object> request) {
        try {
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            Long triggerUserId = Long.valueOf(request.get("triggerUserId").toString());
            Long resourceId = Long.valueOf(request.get("resourceId").toString());
            String resourceType = request.get("resourceType").toString();
            
            SystemNotification notification = notificationService.createThiefSuccessNotification(
                receiverId, triggerUserId, resourceId, resourceType);
            return Result.success(notification);
        } catch (Exception e) {
            log.error("创建小偷偷取成功通知失败", e);
            return Result.error("创建通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建小偷偷取失败通知（内部接口，供其他服务调用）
     */
    @PostMapping("/internal/thief-failed")
    public Result<SystemNotification> createThiefFailedNotification(
            @RequestBody Map<String, Object> request) {
        try {
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            Long triggerUserId = Long.valueOf(request.get("triggerUserId").toString());
            Long resourceId = Long.valueOf(request.get("resourceId").toString());
            String resourceType = request.get("resourceType").toString();
            
            SystemNotification notification = notificationService.createThiefFailedNotification(
                receiverId, triggerUserId, resourceId, resourceType);
            return Result.success(notification);
        } catch (Exception e) {
            log.error("创建小偷偷取失败通知失败", e);
            return Result.error("创建通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 从JWT令牌中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        return jwtUtil.getUserIdFromToken(token);
    }
}